package matcher

import (
	"encoding/xml"
	"regexp"
	"strings"
	"titargo/resource"
)

type ImgMatcher struct {
	atagRegExp *regexp.Regexp
}

func (m *ImgMatcher) SetString(str string, ch chan *resource.Img) {
	atag := m.atagRegExp.FindAllString(str, -1)
	for _, a := range atag {
		src, _ := m.getSrc(a)
		if strings.Contains(src, "javascript") || strings.EqualFold(src, "") || strings.Contains(src, "+") {
			continue
		}

		if !strings.Contains(src, "http://") && !strings.Contains(src, "https://") {
			i := strings.IndexRune(src, '/')
			if i == 0 {
				src = Baseurl + src
			} else {
				continue
			}
		}
		img := &resource.Img{Src: src}
		ch <- img
	}
}

func (m ImgMatcher) getSrc(tag string) (href, content string) {
	inputReader := strings.NewReader(tag)
	decoder := xml.NewDecoder(inputReader)
	for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
		switch token := t.(type) {
		case xml.StartElement:
			for _, attr := range token.Attr {
				attrName := attr.Name.Local
				attrValue := attr.Value
				if strings.EqualFold(attrName, "src") || strings.EqualFold(attrName, "SRC") {
					href = attrValue
				}
			}
		case xml.EndElement:
		case xml.CharData:
			content = string([]byte(token))
		default:
			href = ""
			content = ""
		}
	}
	return href, content
}

func NewImgMatcher() *ImgMatcher {
	m := &ImgMatcher{}
	m.atagRegExp = regexp.MustCompile(`<(img|IMG)[^\<\>]*>`)
	return m
}
